package com.wangdao.wechatmall.controller.wx;

import com.wangdao.wechatmall.bean.vo.admin.BaseRespVo;
import com.wangdao.wechatmall.bean.vo.wx.WXAddressDetailVO;
import com.wangdao.wechatmall.bean.vo.wx.WXAddressListVO;
import com.wangdao.wechatmall.bean.vo.wx.WXAddressVO;
import com.wangdao.wechatmall.exception.AdminVarcharException;
import com.wangdao.wechatmall.service.admin.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * WXAddressController
 * created by feng on 7/11/21
 */
@RestController
@RequestMapping("wx/address")
public class WXAddressController {

    @Autowired
    AddressService addressService;

    // http://192.168.0.103:8083/wx/address/list
    @GetMapping("list")
    public BaseRespVo list() {
        //guang sizhongbin, [11.07.21 10:23]
        //{"errno":0,"data":[{"isDefault":false,"detailedAddress":"安徽省合肥市瑶海区 碧桂园","name":"张松","mobile":"18566549962","id":4},{"isDefault":true,"detailedAddress":"湖北省武汉市洪山区 花山街道软件新城2期","name":"松哥","mobile":"15976753826","id":5}],"errmsg":"成功"}
        List<WXAddressListVO> wxAddressList = addressService.list();

        return BaseRespVo.ok(wxAddressList);
    }

    //http://182.92.235.201:8083/wx/address/detail?id=5
    @GetMapping("detail")
    public BaseRespVo detail(@RequestParam("id") Integer id) {
        WXAddressDetailVO wxAddressDetailVO = addressService.detail(id);
        return BaseRespVo.ok(wxAddressDetailVO);
    }

    //http://182.92.235.201:8083/wx/address/save
    @PostMapping("save")
    public BaseRespVo save(@RequestBody WXAddressVO wxAddressVO) throws AdminVarcharException {

        // Name长度过长
        if (wxAddressVO.getName().length() > 65) {
            throw new AdminVarcharException("请不要输入太长的名字哦!");
        }

        // 地址长度过长
        if (wxAddressVO.getAddress().length() > 100) {
            throw new AdminVarcharException("请不要输入太长的地址哦!");
        }


        // if id = 0 , create new address
        if (wxAddressVO.getId() == 0) {
            Integer InsertedAddressId = addressService.add(wxAddressVO);
            return BaseRespVo.ok(InsertedAddressId);
        }

        // else update address
        Integer affectedRow = addressService.update(wxAddressVO);
        if (affectedRow == 1) {
            //return wxAddressVO id
            return BaseRespVo.ok(wxAddressVO.getId());
        }

        return BaseRespVo.fail();
    }

    //http://182.92.235.201:8083/wx/address/delete
    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map map) {
        Integer id = (Integer) map.get("id");
        Integer affectedRow = addressService.delete(id);

        if (affectedRow == 1) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.fail();
    }


}